<template>
  <el-dialog :append-to-body="true" :before-close="cancelDialog"
             :title="'审计项目立项'" :visible.sync="visible" custom-class="ledger" fullscreen top="5vh"
             width="1200px">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="编制人:" prop="projectManage">
                    {{form.projectManage}}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="立项日期:">
                    <span v-if="showEdit">{{ form.projectDate }}</span>
                    <el-date-picker v-if="!showEdit" placement="bottom-start" v-model="form.projectDate" type="date" placeholder="选择日期"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">基本信息</div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="计划名称:" prop="planName" :rules="{required: true, message: '计划名称不能为空', trigger: ['blur', 'change']}">
                    <span v-if="showEdit">{{ form.planName }}</span>
                    <el-input v-if="!showEdit" v-model="form.planName" placeholder="单击选择计划" @focus="showPlanDialog()" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="项目名称:">
                    <el-input v-model="form.projectName" placeholder="项目名称"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计信息</div>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="被审计单位:" prop="auditedCompanyName" :rules="{required: true, message: '被审计单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.auditedCompanyName" @focus="showTransferDialog(['auditedCompanyId','auditedCompanyName'], 'company', false, 2)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="被审计个人:" prop="auditedUserNames">
                    <el-input v-model="form.auditedUserNames" @focus="showTransferDialog(['auditedUserIds','auditedUserNames'], 'auditedUser', false, form.auditedCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="审计类型:" prop="auditType" :rules="{required: true, message: '审计类型不能为空', trigger: ['blur', 'change']}">
                    <el-select v-model="form.auditType" placeholder="请选择">
                      <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="100px" label="是否披露:">
                    <el-radio-group v-model="form.isPublish">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="form.auditType === 1">
                <el-col :span="12">
                  <el-form-item label-width="140px" label="任职区间:" prop="tenureDates">
                    <el-date-picker placement="bottom-start" v-model="form.tenureDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="审计子类型:" prop="auditTypeSub" :rules="{required: true, message: '审计子类型不能为空', trigger: ['blur', 'change']}">
                    <el-select v-model="form.auditTypeSub" placeholder="请选择">
                      <el-option v-for="dict in dict.type.audit_type_1_sub" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="审计区间:">
                    <el-date-picker placement="bottom-start" v-model="form.auditDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="审计目的:">
                    <el-input v-model="form.auditPurpose"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label-width="140px" label="审计范围:">
                    <el-input v-model="form.auditScope" :autosize="{ minRows: 2}" type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计分工</div>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="审计组组长:" prop="auditLeader" :rules="{required: true, message: '审计组组长不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.auditLeader" @focus="showTransferDialog(['auditLeaderId','auditLeader'], 'auditUser', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="协审单位:" prop="assistCompanyName" :rules="{required: true, message: '协审单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistCompanyName" @focus="showTransferDialog(['assistCompanyId','assistCompanyName'], 'company', false, 3)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="协审单位组长:" prop="assistLeader" :rules="{required: true, message: '协审单位组长不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistLeader" @focus="showTransferDialog(['assistLeaderId','assistLeader'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="被审计单位联络员:" prop="auditedCompanyUserName" :rules="{required: true, message: '被审计单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.auditedCompanyUserName" @focus="showTransferDialog(['auditedCompanyUserId','auditedCompanyUserName'], 'auditedUser', true, form.auditedCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="110px" label="协审单位主审:">
                    <el-input v-model="form.assistJudge" @focus="showTransferDialog(['assistJudgeId','assistJudge'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="审计组成员:">
                    <el-input v-model="form.assistMembers" @focus="showTransferDialog(['assistMemberIds','assistMembers'], 'user', true, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="140px" label="计划工作时间:">
                    <el-date-picker placement="bottom-start" v-model="form.projectDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="实施工作时间:">
                    <el-date-picker placement="bottom-start" v-model="form.workDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计项目文书</div>
              <el-row>
                <el-col>
                  <el-form-item label-width="140px" label="项目审批表:">
                    <web-document :form-data="form" readWord="edit" :pageType="'project'" @createWordFile="wordFileHandle" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
              <el-button type="primary" size="small" icon="el-icon-check" @click="submitAudit">保存送审</el-button>
            </span>
          </div>
        </div>
      </div>
    </div>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
    <ChosePlan ref="ChosePlan" @setValue="planDataHandle"/>
  </el-dialog>
</template>

<script>
import FormTransfer from "@/components/form/transfer";
import ChosePlan from "@/components/audited/ChosePlan";
import {getProject, projectSubmit, submitAudit} from "@/api/adis/project/project";
import WebDocument from '@/components/form/webDocument.vue';

export default {
  components: {
    FormTransfer,
    ChosePlan,
    WebDocument
  },
  dictTypes: ['audit_type', 'audit_type_1_sub', 'audit_way', 'organization_type'],
  data() {
    return {
      visible: false,
      loading: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
      planDialog: false,
      showEdit: false,
      form: {
        auditType: '',
      },
      data: [],
      fileList: [], // 文件
      dateFields: ['audit', 'project', 'work', 'prepare', 'apply', 'finish', 'tenure'],
    }
  },
  methods: {
    init(params) {
      this.form.projectManageId = params.compilerId
      this.form.projectManage = params.compiler
      this.$set(this.form, "projectDate", new Date().toISOString())
      this.$nextTick(async () => {
        if (params.projectId) {
          const response = await getProject(params.projectId);
          const data = { ...response.data.data };

          // 根据字符集创建对应的时间数组
          this.dateFields.forEach(field => {
            const StartDate = data[`${field}StartDate`];
            const EndDate = data[`${field}EndDate`];
            const datesField = `${field}Dates`;
            if (StartDate && EndDate) {
              this.$set(data, datesField, [StartDate, EndDate]);
            } else {
              this.$set(data, datesField, []);
            }
          });
          this.form = data;
        }
        this.visible = true;
      })
      this.showEdit = params.showEdit;
    },
    // 项目表单提交
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(this.form.auditDates) {
            this.form.auditStartDate = this.form.auditDates[0];
            this.form.auditEndDate = this.form.auditDates[1];
          }
          if(this.form.planDates) {
            this.form.planStartDate = this.form.planDates[0];
            this.form.planEndDate = this.form.planDates[1];
          }
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          // console.log(this.form);
          this.loading = true;

          this.dateFields.forEach(field => {
            const dates = this.form[`${field}Dates`];
            if (dates) {
              this.form[`${field}StartDate`] = dates[0];
              this.form[`${field}EndDate`] = dates[1];
            }
          });
          projectSubmit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          this.loading = true;

          this.dateFields.forEach(field => {
            const dates = this.form[`${field}Dates`];
            if (dates) {
              this.form[`${field}StartDate`] = dates[0];
              this.form[`${field}EndDate`] = dates[1];
            }
          });
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    //重置表单
    cancelDialog() {
      this.visible = false;
      this.form = {};
      this.$refs['dataForm'].resetFields()
      this.$emit('cancelDialog', {})
    },
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      // console.log(this.form, 'this.form')
      this.transferDialogType = ''
    },
    showPlanDialog() {
      this.$nextTick(() => {
        this.$refs.ChosePlan.initParams({hasProject: false, isTermination: false});
      })
    },
    planDataHandle(row) {
      this.planDialog = false;
      this.templateForm = this.form;
      let combinedFormData = this.form;
      combinedFormData.planId = row.planId;
      combinedFormData.planName = row.planName;
      combinedFormData.projectName = row.planName;
      combinedFormData.auditType = row.auditType;
      combinedFormData.auditTypeSub = row.auditTypeSub;
      combinedFormData.auditStartDate = row.auditStartDate;
      combinedFormData.auditEndDate = row.auditEndDate;
      combinedFormData.planStartDate = row.planStartDate;
      combinedFormData.planEndDate = row.planEndDate;

      combinedFormData.auditedCompanyId = row.auditedCompanyId;
      combinedFormData.auditedCompanyName = row.auditedCompanyName;
      combinedFormData.auditedUserIds = row.auditedUserIds;
      combinedFormData.auditedUserNames = row.auditedUserNames;

      if(row.auditStartDate && row.auditEndDate) {
        combinedFormData.auditDates = [row.auditStartDate, row.auditEndDate];
      }
      if(row.planStartDate && row.planEndDate) {
        combinedFormData.projectDates = [row.planStartDate, row.planEndDate];
      }
      this.$set(this, "form", Object.assign({}, this.form, combinedFormData));
    },
    clearPlanForm() {
      this.$set(this, "form", this.templateForm)
    },
    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "projectId", e.id);
    }
  }
}
</script>
<style scoped>

</style>
